<?php

namespace App\Services;

use App\Models\PhoneRecord;
use App\Models\Task;
use Illuminate\Support\Facades\Log;
use Twilio\Rest\Client;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class TwilioService
{
    protected $task;

    protected $phoneRecord;

    public function __construct(Task $task,PhoneRecord $phoneRecord)
    {
        $this->task = $task;
        $this->phoneRecord = $phoneRecord;
    }

    //创建SID
    public function createSid($name=''){
        $application = app('Twilio')
            ->applications
            ->create($name,
                array(
                    "voiceMethod" => "GET",
                    "voiceUrl" =>  env('APP_URL').'/api/xml'
                )
            );
        return $application->sid;
    }

    //更新SID
    /**
     *更新XML电话路径
     *@param  $apps 应用id
     * @param $to  会员电话
     * @param $from  后台电话
     * @param $id 会员id
     * @param  $user_id 台用户id
     * @peram $task_id  任务id
     */
    public function updateSid($sid, $to, $from,$id,$user_id,$task_id='',$phone_setting_id=''){
        $url = env('APP_URL')."/api/xml?to={$to}&from={$from}&id={$id}&user_id={$user_id}&task_id={$task_id}&phone_setting_id={$phone_setting_id}";
        $res = $application = app('Twilio')->applications($sid)
            ->update(array(
//                    "smsUrl" => "http://demo.twilio.com/docs/sms.xml",
                    "voiceUrl" => $url
                )
            );
        Log::info('更改XML电话地址',['data'=>$url,'res'=>$res]);
    }
    //删除SID
    public function deleteSid($sid=''){
        $res = app('Twilio')->applications($sid)
            ->delete();
        return $res;
    }
    //获取账号下电话列表
    public function numberList($sid, $token){
        try{
            $sid    = $sid;
            $token  = $token;
            $twilio = new Client($sid, $token);

            $data = [];
            $incomingPhoneNumbers = $twilio->incomingPhoneNumbers
                ->read(array("phoneNumber" => "852"));

            foreach ($incomingPhoneNumbers as $record) {
                $data[] = $record->phoneNumber;
            }
            return $data;
        }catch (\Exception $e){
           return [
               'status'=>422,
               'message'=>'无效的配置',
               'msg'=>$e->getMessage(),
               'type'=>'twilio'
           ];
        }
    }
    //购买电话号
    public function buy(){
        if (!app()->environment('production')) {
            $number = '+'.str_pad(random_int(1, 99999999), 4, 0, STR_PAD_LEFT);
            $data['friendly_name'] = $number;
            $data['phone_number'] = $number;
            $data['capabilities'] = json_encode([
                'voice'=>1,
                'SMS' => 0,
                'MMS' => 0,
                'fax' =>0
            ]);
        }else{
            try{
                $numbers = app('Twilio')->availablePhoneNumbers('HK')->local->read(
                    array("voiceEnabled" => "true")
                );
                $number = app('Twilio')->incomingPhoneNumbers
                    ->create(
                        array(
                            "phoneNumber" => $numbers[0]->phoneNumber,
                        )
                    );
                $data = $number;
                Log::info('购买twilio电话返回数据',['data'=>$number]);
            }catch (\Exception $exception){
                Log::error('购买twilio电话',['data'=>$exception]);
            }
        }
        return $data;
    }

    /**
     * 修改task表状态字段
     * @param $validatedData
     * $validatedData['id']   fs_user_id
     * $validatedData['task_id']  task_id
     * 0 完成 1已完成 3逾期未完成  4逾期完成
     */
    public function taskStatus($validatedData){
        if(empty($validatedData['task_id'])){
            return;
        }
        $task = $this->task::find($validatedData['task_id']);
        if($task){
            //打通电话人数
            $call_count = $task->fsUserTask->where('status',1)->count();
            //任务会员人数
            $count = $task->count;
            //（完成度100%）任务的人数等于 任务会员表status为1 的数量
            if($call_count == $count){
                //最后一通电话的通话时间
                $call_end_time = $task->fsUserTask->sortByDesc('call_time')->first()->call_time;
                //任务结束时间
                $task_end_time = $task->end_time;

                if($call_end_time <= $task_end_time ){
                    //完成任务 1
                    DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 1]);
                }else{
                    //逾期完成任务 4
                    DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 4]);
                }
            }elseif ($task->end_time < date('Y-m-d H:i:s',time()) && $task->status === 0){
                //当前时间大于任务结束时间
                //逾期未完成 3
                DB::table('tasks')->where('id',$validatedData['task_id'])->update(['status' => 3]);
            }
        }
    }
}